<template>
  <div class="content">
    <a-form ref="formRef" :model="formState" :rules="rules">
      <a-form-item ref="nickname" label="考生姓名" name="nickname">
        <a-input v-model:value="formState.nickname" placeholder="请输入姓名" />
      </a-form-item>

      <a-form-item ref="nickname_py" label="考生拼音" name="nickname_py">
        <a-input
          v-model:value="formState.nickname_py"
          placeholder="请输入姓名拼音"
        />
      </a-form-item>

      <a-form-item label="性别" name="gender">
        <a-select
          v-model:value="formState.gender"
          disabled
          placeholder="请选择性别"
        >
          <a-select-option value="0">女</a-select-option>
          <a-select-option value="1">男</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item ref="birthday" label="出生日期" name="birthday">
        <a-date-picker
          v-model:value="formState.birthday"
          type="date"
          format="YYYY-MM-DD"
          placeholder="请选择出生日期"
          style="width: 100%"
          @change="panelChange1"
        />
      </a-form-item>

      <a-form-item ref="username" label="身份证号" name="username">
        <a-input
          v-model:value="formState.username"
          placeholder="请输入身份证号"
        />
      </a-form-item>

      <a-form-item ref="avatar" label="照片（电子版）" name="avatar">
        <a-upload
          v-model:file-list="fileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
        >
          <img v-if="imageUrl" height="120" :src="imageUrl" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">点击上传</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item ref="mobile" label="联系方式" name="mobile">
        <a-input
          v-model:value="formState.mobile"
          placeholder="请输入联系方式"
        />
      </a-form-item>

      <a-form-item ref="email" label="邮箱地址" name="email">
        <a-input v-model:value="formState.email" placeholder="请输入邮箱地址" />
      </a-form-item>

      <a-form-item ref="huji" label="户籍" name="huji">
        <a-input v-model:value="formState.huji" placeholder="请输入户籍" />
      </a-form-item>

      <a-form-item ref="address" label="家庭住址" name="address">
        <a-input
          v-model:value="formState.address"
          placeholder="请输入家庭住址"
        />
      </a-form-item>

      <a-form-item ref="school" label="目前就读学校/培训机构" name="school">
        <a-input
          v-model:value="formState.school"
          placeholder="请输入目前就读学校/培训机构"
        />
      </a-form-item>

      <a-form-item
        ref="username_endtime"
        label="证件有效期"
        name="username_endtime"
      >
        <a-date-picker
          v-model:value="formState.username_endtime"
          type="date"
          format="YYYY-MM-DD"
          placeholder="请选择证件有效期"
          style="width: 100%"
          :disabled-date="disabledDate"
          :disabled-time="disabledDateTime"
          :show-time="{ defaultValue: moment('HH:mm:ss') }"
          @change="panelChange2"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="onSubmit" class="button"
          >提 交</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import moment from "moment";
import { defineComponent, onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import { uploadImg, imgUrl, getUserInfo, setUserInfo } from "@/api/https.js";
export default defineComponent({
  setup() {
    const formRef = ref();
    const formState = ref({
      user_id: JSON.parse(localStorage.getItem("info")).user_id,
      nickname: "", // 考生姓名
      nickname_py: "", // 考生拼音
      gender: null, // 性别
      birthday: null, // 出生日期
      username: "", // 身份证号
      avatar: "", // 照片（电子版）
      mobile: "", // 联系方式
      email: "", // 邮箱地址
      huji: "", // 户籍
      address: "", // 家庭住址
      school: "", // 目前就读学校/培训机构
      username_endtime: null, //证件有效期
    });
    // 身份证正则
    let validatePass = async (rule, value) => {
      console.log("正则---", value);
      const zz = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!zz.test(value)) {
        return Promise.reject("身份证格式填写错误");
      } else {
        return Promise.resolve();
      }
    };
    // 电话正则
    let phoneZZ = async (rule, value) => {
      const zz = /^1[3456789]\d{9}$/;
      if (!zz.test(value)) {
        return Promise.reject("手机号格式错误");
      } else {
        return Promise.resolve();
      }
    };
    // 邮箱正则
    let emailZZ = async (rule, value) => {
      const zz =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!zz.test(value)) {
        return Promise.reject("邮箱格式错误");
      } else {
        return Promise.resolve();
      }
    };
    const range = (start, end) => {
      const result = [];

      for (let i = start; i < end; i++) {
        result.push(i);
      }

      return result;
    };
    const disabledDate = (current) => {
      return current && current < moment().endOf("day");
    };

    const disabledDateTime = () => {
      return {
        disabledHours: () => range(0, 24).splice(4, 20),
        disabledMinutes: () => range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    };
    const rules = {
      nickname: [
        {
          required: true,
          message: "请输入姓名",
          trigger: "blur",
        },
      ],
      nickname_py: [
        {
          required: true,
          message: "请输入姓名",
          trigger: "blur",
        },
      ],
      gender: [
        {
          required: true,
          message: "请选择性别",
          trigger: "blur",
        },
      ],
      birthday: [
        {
          required: true,
          message: "请选择出生日期",
          trigger: "change",
        },
      ],
      username: [
        {
          required: true,
          message: "请输入身份证号",
          trigger: "blur",
        },
        {
          validator: validatePass,
          trigger: "blur",
        },
      ],
      avatar: [
        {
          required: true,
          message: "请上传照片",
          trigger: "blur",
        },
      ],
      mobile: [
        {
          required: true,
          message: "请输入联系方式",
          trigger: "blur",
        },
        {
          validator: phoneZZ,
          trigger: "blur",
        },
      ],
      email: [
        {
          required: true,
          message: "请输入邮箱地址",
          trigger: "blur",
        },
        {
          validator: emailZZ,
          trigger: "blur",
        },
      ],
      huji: [
        {
          required: true,
          message: "请输入户籍",
          trigger: "blur",
        },
      ],
      address: [
        {
          required: true,
          message: "请输入家庭住址",
          trigger: "blur",
        },
      ],
      school: [
        {
          required: true,
          message: "请输入目前就读学校/培训机构",
          trigger: "blur",
        },
      ],
      username_endtime: [
        {
          required: true,
          message: "请选择证件有效期",
          trigger: "change",
        },
      ],
    };

    const onSubmit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          const data = await setUserInfo(formState.value);
          if (data.code == 1) {
            getInfo();
            message.success(`${data.msg}`);
          } else {
            message.error(`${data.msg}`);
          }
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref("");

    const beforeUpload = async (file) => {
      let param = new FormData();
      param.append("file", file);
      const data = await uploadImg(param);
      formState.value.avatar = data.data.url;
      imageUrl.value = imgUrl + data.data.url;
      message.info(`${data.msg}`);
      console.log("图片上传---", data);
    };

    const panelChange1 = (val, mode) => {
      formState.value.birthday = mode;
    };

    const panelChange2 = (val, mode) => {
      formState.value.username_endtime = mode;
    };

    // 获取用户信息
    const getInfo = async () => {
      const data = await getUserInfo({ user_id: formState.value.user_id });
      console.log("data---", data.data);
      imageUrl.value = imgUrl + data.data.avatar;
      data.data.username_endtime = getTime(data.data.username_endtime);
      data.data.birthday = getTime(data.data.birthday);
      data.data["user_id"] = data.data.id;
      data.data.gender = String(data.data.gender);
      formState.value = data.data;
      console.log(formState);
    };

    const getTime = (time) => {
      const endTime = new Date(time * 1000);
      const endFullYear = endTime.getFullYear();
      const endMonth =
        endTime.getMonth() + 1 >= 10
          ? endTime.getMonth() + 1
          : "0" + (endTime.getMonth() + 1);
      const endDate =
        endTime.getDate() >= 10 ? endTime.getDate() : "0" + endTime.getDate();
      console.log(`${endFullYear}-${endMonth}-${endDate}`);
      return `${endFullYear}-${endMonth}-${endDate}`;
    };

    onMounted(() => {
      getInfo();
    });

    return {
      formRef,
      other: "",
      formState,
      rules,
      onSubmit,
      fileList,
      beforeUpload,
      imageUrl,
      loading,
      panelChange1,
      panelChange2,
      disabledDate,
      disabledDateTime,
      moment,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  max-width: 500px;
  margin-top: 40px;

  .ant-form-item {
    flex-direction: var(--bannerFlex);
    justify-content: center;
  }

  .button {
    margin-top: 20px;
    width: 100%;
    height: 45px;
    background: #554de6;
    border-radius: 25px;
    font-size: var(--txtSize);
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
  }

  .buttons {
    text-align: center;
    font-size: var(--txtSize);
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #808080;
    cursor: pointer;
  }

  /deep/ .ant-col {
    width: 300px;
  }
  /deep/ .ant-form-item-label {
    width: 140px;
    margin-right: 20px;
  }
}
</style>
